package utils

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"time"
)

type LogLevel string

const (
	INFO  LogLevel = "INFO"
	WARN  LogLevel = "WARN"
	ERROR LogLevel = "ERROR"
)

var (
	Logger  *log.Logger
	LogFile *os.File
)

func InitLogger(logDir string) error {
	if err := os.MkdirAll(logDir, os.ModePerm); err != nil {
		return fmt.Errorf("创建日志目录失败: %v", err)
	}

	logFile := filepath.Join(logDir, time.Now().Format("20060102")+".log")
	file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		return fmt.Errorf("创建日志文件失败: %v", err)
	}

	Logger = log.New(file, "", 0)
	LogFile = file
	return nil
}

func Log(level LogLevel, format string, v ...interface{}) {
	if Logger == nil {
		return
	}
	timestamp := time.Now().Format("2006年01月02日 15:04:05")
	msg := fmt.Sprintf(format, v...)
	Logger.Printf("[%s] %s: %s\r\n", timestamp, level, msg)
	fmt.Printf("[%s] %s: %s\r\n", timestamp, level, msg)
}

func CloseLogger() {
	if LogFile != nil {
		LogFile.Close()
	}
}
